<?php
/* 
Plugin Name: WoW Armory 
Plugin URI: http://timsworld.nfshost.com/wordpress-plugins/wow-armory-wp-plugin/ 
Description: Shows your character's Armory info  
Version: 5.0
Author: Tim (SeiferTim) Hely
Author URI: http://timsworld.nfshost.com
*/  



if (isset($_GET['deleteit']) && isset($_GET['delete'])) {
	$clear_count = 0;
	foreach( (array) $_GET['delete'] as $clear_name ) {
		delete_option($clear_name);
		$clear_count++;
	}
	?>
	<div id="message" class="updated fade">
		<p><?php echo sprintf('Cleared %s caches.', $clear_count); ?></p>
	</div>
	<?php
}


require_once(ABSPATH . 'wp-includes/class-snoopy.php');

	class WoWArmory {
    var $plugin_folder = '';
/* -- List of Profession Icons -- */
		 var $prof_img = array(
			"Jewelcrafting"	=>	'inv_misc_gem_02',
			"Inscription" => 'inv_inscription_tradeskill01',
			"Leatherworking" => 'inv_misc_armorkit_17',
			"Skinning" =>	'inv_misc_pelt_wolf_01',
			"Herbalism"	=>	'spell_nature_naturetouchgrow',
			"Alchemy" =>	'trade_alchemy',
			"Blacksmithing" => 'trade_blacksmithing',
			"Engineering" => 'trade_engineering',
			"Enchanting" =>	'trade_engraving',
			"Mining" =>	'trade_mining',
			"Tailoring" =>	'trade_tailoring',
		);
		/* ------------------------------ */
		
		
		
		/* --- Option Counts -- */
		
		var  $opts = array(
			// Human Male
			1 => array(
				0 => array(
					'ha' => 23,
					'hc' => 12,
					'fa' => 29,
					'sk' => 14,
					'fh' => 6,
					'fc' => 12,
				),
				// Human Female
				1 => array (
					 'ha' => 16,
					 'hc' => 12,
					 'fa' => 23,
					 'sk' => 14,
					 'fh' => 8,
					 'fc' => 12,
				),
			),
		
			
			2 => array(
				//Orc Male
				0 => array(
					'ha' => 12,
					'hc' => 10,
					'fa' => 17,
					'sk' => 13,
					'fh' => 6,
					'fc' => 10,
				),
				// Orc Female
				1 => array (
					 'ha' => 11,
					'hc' => 10,
					'fa' => 17,
					'sk' => 17,
					'fh' => 10,
					'fc' => 10,
				),
			),
			
			3 => array(
				//Dwarf Male
				0 => array(
					'ha' => 18,
					'hc' => 12,
					'fa' => 19,
					'sk' => 13,
					'fh' => 5,
					'fc' => 12,
				),
				// Dwarf Female
				1 => array (
					'ha' => 15,
					'hc' => 12,
					'fa' => 19,
					'sk' => 21,
					'fh' => 10,
					'fc' => 12,
				),
			),
			
			4 => array(
				// Night Elf Male
				0 => array(
					'ha' => 11,
					'hc' => 9,
					'fa' => 17,
					'sk' => 11,
					'fh' => 9,
					'fc' => 10,
				),
				// Night Elf Female
				1 => array (
					'ha' => 11,
					'hc' => 9,
					'fa' => 17,
					'sk' => 11,
					'fh' => 5,
					'fc' => 10,
				),
			),
			
			5 => array(
				//Forsaken Male
				0 => array(
					'ha' => 14,
					'hc' => 9,
					'fa' => 19,
					'sk' => 5,
					'fh' => 7,
					'fc' => 9,
				),
				// Forsaken Female
				1 => array (
					'ha' => 14,
					'hc' => 9,
					'fa' => 19,
					'sk' => 5,
					'fh' => 16,
					'fc' => 9,
				),
			),
			
			6 => array(
				//Tauren Male
				0 => array(
					'ha' => 11,
					'hc' => 2,
					'fa' => 7,
					'sk' => 13,
					'fh' => 4,
					'fc' => 2,
				),
				// Tauren Female
				1 => array (
					'ha' => 12,
					'hc' => 2,
					'fa' => 9,
					'sk' => 21,
					'fh' => 6,
					'fc' => 2,
				),
			),
			
			7 => array(
				// Gnome Male
				0 => array(
					'ha' => 11,
					'hc' => 11,
					'fa' => 13,
					'sk' => 9,
					'fh' => 6,
					'fc' => 11,
				),
				// Gnome Female
				1 => array (
					'ha' => 11,
					'hc' => 11,
					'fa' => 13,
					'sk' => 9,
					'fh' => 7,
					'fc' => 11,
				),
			),
			
			8 => array(
				// Troll Male
				0 => array(
					'ha' => 9,
					'hc' => 12,
					'fa' => 11,
					'sk' => 17,
					'fh' => 5,
					'fc' => 12,	
				),
				// Troll Female
				1 => array (
					 'ha' => 9,
					'hc' => 12,
					'fa' => 9,
					'sk' => 17,
					'fh' => 10,
					'fc' => 12,
				),
			),
			
			10 => array(
				//Blood Elf Male
				0 => array(
					'ha' => 19,
					'hc' => 12,
					'fa' => 19,
					'sk' => 18,
					'fh' => 10,
					'fc' => 12,
				),
				// Blood Elf Female
				1 => array (
					'ha' => 15,
					'hc' => 12,
					'fa' => 19,
					'sk' => 18,
					'fh' => 9,
					'fc' => 12,
				),
			),
			
			11 => array(
				//Draenei Male
				0 => array(
					'ha' => 15,
					'hc' => 9,
					'fa' => 19,
					'sk' => 14,
					'fh' => 6,
					'fc' => 9,
				),
				// Draenei Female
				1 => array (
					'ha' => 13,
					'hc' => 9,
					'fa' => 19,
					'sk' => 16,
					'fh' => 7,
					'fc' => 9,
				),
			),
		);

		/* -- List of Models -- */
		 var $modelNames = array(
			1 => array(
					0 => 'humanmale',
					1 => 'humanfemale',
				),
			2 => array(
					0 => 'orcmale',
					1 => 'orcfemale',
				),
			3 => array(
					0 => 'dwarfmale',
					1 => 'dwarffemale',
				),
			4 => array(
					0 => 'nightelfmale',
					1 => 'nightelffemale',
				),
			5 => array(
					0 => 'scourgemale',
					1 => 'scourgefemale',
				),
			6 => array(
					0 => 'taurenmale',
					1 => 'taurenfemale',
				),
			7 => array(
					0 => 'gnomemale',
					1 => 'gnomefemale',
				),
			8 => array(
					0 => 'trollmale',
					1 => 'trollfemale',
				),
			10 => array(
					0 => 'bloodelfmale',
					1 => 'bloodelffemale',
				),
			11 => array(
					0 => 'draeneimale',
					1 => 'draeneifemale',
				),
		);
		/* -------------------- */
		
    var $default_options = array(
            'cname' => '', 
            'realm' => '',
            'realmtype' => '',
            'show_top' => true,
            'show_g' => true,
            'show_p' => true,
            'show_a' => true,
            'lang' => 'En',
            'linkback' => false,
            'talents' => true,
            'show3D' => false,
            'hair' => 0,
            'hairColor' => 0,
            'face' => 0,
            'skinColor' => 0,
            'facialHair' => 0,
            'facialHairColor' => 0,
    );
    
    
			

  function WoWArmory() {
        $this->plugin_folder = get_option('home').'/'.PLUGINDIR.'/wow-armory/';
        wp_enqueue_script('wowhead',"http://www.wowhead.com/widgets/power.js");
        wp_enqueue_style('wow_armory_css', get_bloginfo('wpurl') . '/wp-content/plugins/wow-armory/css/style.css');      
    }

    function init() {
        if (!$options = get_option('widget_wow_armory'))
            $options = array();
            
        $widget_ops = array('classname' => 'widget_wow_armory', 'description' => 'WoW Armory');
        $control_ops = array('width' => 250, 'height' => 100, 'id_base' => 'wowarmory');
        $name = 'WoW Armory';
        
        $registered = false;
        foreach (array_keys($options) as $o) {
            if (!isset($options[$o]['cname']))
                continue;
                
            $id = "wowarmory-$o";
            $registered = true;
            wp_register_sidebar_widget($id, $name, array(&$this, 'widget'), $widget_ops, array( 'number' => $o ) );
            wp_register_widget_control($id, $name, array(&$this, 'control'), $control_ops, array( 'number' => $o ) );
        }
        if (!$registered) {
            wp_register_sidebar_widget('wowarmory-1', $name, array(&$this, 'widget'), $widget_ops, array( 'number' => -1 ) );
            wp_register_widget_control('wowarmory-1', $name, array(&$this, 'control'), $control_ops, array( 'number' => -1 ) );
        }
    }

    function widget($args, $widget_args = 1) {
        
        extract($args);
        global $post;

        if (is_numeric($widget_args))
            $widget_args = array('number' => $widget_args);
        $widget_args = wp_parse_args($widget_args, array( 'number' => -1 ));
        extract($widget_args, EXTR_SKIP);
        $options_all = get_option('widget_wow_armory');
        if (!isset($options_all[$number]))
            return;

        $options = $options_all[$number];

        echo $before_widget;
        echo $before_title . ' Armory for ' . $options["cname"] . $after_title;	   
        echo '<div id="armory-'.$number.'" class="armory_display">';
        $armory = $this->getArmory($options);
        echo $armory['content'];
        echo "</div>$after_widget";
    }

		function control($widget_args = 1) {
				global $wp_registered_widgets;
				static $updated = false;
				if ( is_numeric($widget_args) )
						$widget_args = array('number' => $widget_args);
				$widget_args = wp_parse_args($widget_args, array('number' => -1));
				extract($widget_args, EXTR_SKIP);
				$options_all = get_option('widget_wow_armory');
				if (!is_array($options_all))
						$options_all = array();  
						
				if (!$updated && !empty($_POST['sidebar'])) {
						$sidebar = (string)$_POST['sidebar'];

						$sidebars_widgets = wp_get_sidebars_widgets();
						if (isset($sidebars_widgets[$sidebar]))
								$this_sidebar =& $sidebars_widgets[$sidebar];
						else
								$this_sidebar = array();

						foreach ($this_sidebar as $_widget_id) {
								if ('widget_wow_armory' == $wp_registered_widgets[$_widget_id]['callback'] && isset($wp_registered_widgets[$_widget_id]['params'][0]['number'])) {
										$widget_number = $wp_registered_widgets[$_widget_id]['params'][0]['number'];
										if (!in_array("wowarmory-$widget_number", $_POST['widget-id']))
												unset($options_all[$widget_number]);
								}
						}
						
						foreach ((array)$_POST['widget_wow_armory'] as $widget_number => $posted) {
								if (!isset($posted['cname']) && isset($options_all[$widget_number]))
										continue;
								
								$options = array();
								$options['cname'] = stripslashes($posted['cname']);
								$options['realm'] = stripslashes($posted['realm']);
								$options['realmtype'] = $posted['realmtype'];
								$options['show_g'] = $posted['show_g'];
								$options['show_p'] = $posted['show_p'];
								$options['show_a'] = $posted['show_a'];
								$options['lang'] = $posted['lang'];
								$options['linkback'] = $posted['linkback'];
								$options['talents'] = $posted['talents'];
								$options['show3D'] = $posted['show3D'];
								$options['hair'] = $posted['hair'];
								$options['hairColor'] = $posted['hairColor'];
								$options['face'] = $posted['face'];
								$options['skinColor'] = $posted['skinColor'];
								$options['facialHair'] = $posted['facialHair'];
								$options['facialHairColor'] = $posted['facialHairColor'];
								$options['show_top'] = $posted['show_top'];
								$options_all[$widget_number] = $options;
						}
						update_option('widget_wow_armory', $options_all);
						$updated = true;
				}

				if (-1 == $number) {
						$number = '%i%';
						$values = $this->default_options;
				}
				else {
						$values = $options_all[$number];
				}        
				
				?>
				<label for="widget_wow_armory[<?php echo $number; ?>][cname]">Character Name:</label>
				<input class="widefat" id="widget_wow_armory-<?php echo $number; ?>-cname" name="widget_wow_armory[<?php echo $number; ?>][cname]" type="text" value="<?php echo stripslashes($values['cname']); ?>" />
				<label for="widget_wow_armory[<?php echo $number; ?>][realm]">Realm:</label>
				<input class="widefat" id="widget_wow_armory-<?php echo $number; ?>-realm" name="widget_wow_armory[<?php echo $number; ?>][realm]" type="text" value="<?php echo stripslashes($values['realm']); ?>" />
				<label for="widget_wow_armory[<?php echo $number; ?>][realmtype]">Realm Type:</label>
				<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-realmtype" name="widget_wow_armory[<?php echo $number; ?>][realmtype]" />
					<option value="US"<?php echo $values['realmtype'] == 'US' ? ' selected="selected"' : ''; ?>>US</option>
					<option value="EU"<?php echo $values['realmtype'] == 'EU' ? ' selected="selected"' : ''; ?>>EU</option>
				</select>
				<label for="show_top">Show Top: </label>
				<input id="widget_wow_armory-<?php echo $number; ?>-show_top" name="widget_wow_armory[<?php echo $number; ?>][show_top]" type="checkbox" value="1"<?php echo $values['show_top'] ? ' checked' : ''; ?>/>
				<br />
				<label for="talents">Show Talents:</label>
				<input id="widget_wow_armory-<?php echo $number; ?>-talents" name="widget_wow_armory[<?php echo $number; ?>][talents]" type="checkbox" value="1"<?php echo $values['talents'] ? ' checked' : ''; ?>/>
				<br />
				<label for="show_g">Show Gear:</label>
				<input id="widget_wow_armory-<?php echo $number; ?>-show_g" name="widget_wow_armory[<?php echo $number; ?>][show_g]" type="checkbox" value="1"<?php echo $values['show_g'] ? ' checked' : ''; ?>/>
				<br/>
				<label for="show_p">Show Professions:</label>
				<input id="widget_wow_armory-<?php echo $number; ?>-show_p" name="widget_wow_armory[<?php echo $number; ?>][show_p]" type="checkbox" value="1"<?php echo $values['show_p'] ? ' checked' : ''; ?>/>
				<br/>
				<label for="show_a">Show Achievements:<label>
				<input id="widget_wow_armory-<?php echo $number; ?>-show_a" name="widget_wow_armory[<?php echo $number; ?>][show_a]" type="checkbox" value="1"<?php echo $values['show_a'] ? ' checked' : ''; ?>/>
				<br />
				<label for "widget_wow_armory[<?php echo $number; ?>][lang]">Language</label>
				<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-lang" name="widget_wow_armory[<?php echo $number; ?>][lang]" />
					<option value="en"<?php echo $values['lang'] == 'en' ? ' selected="selected"' : ''; ?>>English</option>
					<option value="de"<?php echo $values['lang'] == 'de' ? ' selected="selected"' : ''; ?>>Deutsch</option>
					<option value="es"<?php echo $values['lang'] == 'es' ? ' selected="selected"' : ''; ?>><?php echo html_entity_decode('Espa&Atilde;&plusmn;ol'); ?></option>
					<option value="fr"<?php echo $values['lang'] == 'fr' ? ' selected="selected"' : ''; ?>><?php echo html_entity_decode('Fran&Atilde;&sect;ais'); ?></option>
					<option value="ru"<?php echo $values['lang'] == 'ru' ? ' selected="selected"' : ''; ?>>Pycc<?php echo html_entity_decode('&ETH;&ordm;&ETH;&cedil;&ETH;&sup1;'); ?></option>
				</select><br/>
				<label for="linkback">Show an Optional link back to Tim's World?</label>
				<input id="widget_wow_armory-<?php echo $number; ?>-linkback" name="widget_wow_armory[<?php echo $number; ?>][linkback]" type="checkbox" value="1"<?php echo $values['linkback'] ? ' checked' : ''; ?> /><br/>
				<label for="show3D">Show a 3D Model of your Character?</label>
				<input id="widget_wow_armory-<?php echo $number; ?>-show3D" name="widget_wow_armory[<?php echo $number; ?>][show3D]" type="checkbox" value="1"<?php echo $values['show3D'] ? ' checked' : ''; ?> />
				<div id="3DOnly">
					<?php 
					if (stripslashes($values['cname']) != '' && stripslashes($values['realm']) != '') {
						$armory = $this->getArmory(array(
								'cname' => stripslashes($values['cname']) ,
								'realm' => stripslashes($values['realm']),
								'realmType' => stripslashes($values['realmType']),
								'show_g' => 0,
								'show_p' => 0,
								'show_a' => 0,
								'lang' => $values['lang'],
								'linkback' => 0,
								'talents' => 0,
								'show3D' => 1,
								'hair' => $values['hair'],
								'hairColor' => $values['hairColor'],
								'face' => $values['face'],
								'skinColor' => $values['skinColor'],
								'facialHair' => $values['facialHair'],
								'facialHairColor' => $values['facialHairColor'],
								'show_top' => 0,
							)
						);
						echo $armory['content'];
						$thisChar = $this->opts[$armory['raceid']][$armory["genderid"]];
						$model = $this->modelNames[$armory['raceid']][$armory["genderid"]];
					}
					?>
					<label for="hair">Hair Style</label>
					<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-hair" name="widget_wow_armory[<?php echo $number; ?>][hair]" />
						<?php for ($i = 0; $i<=$thisChar['ha'];$i++) { ?> 
						<option value="<?php echo $i; ?>"<?php echo ($values['hair'] == $i) ? ' selected' : ''; ?>><?php echo $i; ?></option>
						<?php } ?>
					</select>
					<label for="hairColor">Hair Color</label>
					<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-hairColor" name="widget_wow_armory[<?php echo $number; ?>][hairColor]" />
						<?php for ($i = 0; $i<=$thisChar['hc'];$i++) { ?> 
						<option value="<?php echo $i; ?>"<?php echo ($values['hairColor'] == $i) ? ' selected' : ''; ?>><?php echo $i; ?></option>
						<?php } ?>
					</select>
					<label for="face">Face</label>
					<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-face" name="widget_wow_armory[<?php echo $number; ?>][face]" />
						<?php for ($i = 0; $i<=$thisChar['fa'];$i++) { ?> 
						<option value="<?php echo $i; ?>"<?php echo ($values['face'] == $i) ? ' selected' : ''; ?>><?php echo $i; ?></option>
						<?php } ?>
					</select>
					<label for="skinColor">Skin Color</label>
					<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-skinColor" name="widget_wow_armory[<?php echo $number; ?>][skinColor]" />
						<?php for ($i = 0; $i<=$thisChar['sk'];$i++) { ?> 
						<option value="<?php echo $i; ?>"<?php echo ($values['skinColor'] == $i) ? ' selected' : ''; ?>><?php echo $i; ?></option>
						<?php } ?>
					</select>
					<label for="facialHair">Facial Hair</label>
					<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-facialHair" name="widget_wow_armory[<?php echo $number; ?>][facialHair]" />
						<?php for ($i = 0; $i<=$thisChar['fh'];$i++) { ?> 
						<option value="<?php echo $i; ?>"<?php echo ($values['facialHair'] == $i) ? ' selected' : ''; ?>><?php echo $i; ?></option>
						<?php } ?>
					</select>
					<label for="facialHairColor">Facial Hair Color</label>
					<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-facialHairColor" name="widget_wow_armory[<?php echo $number; ?>][facialHairColor]" />
						<?php for ($i = 0; $i<=$thisChar['fc'];$i++) { ?> 
						<option value="<?php echo $i; ?>"<?php echo ($values['facialHairColor'] == $i) ? ' selected' : ''; ?>><?php echo $i; ?></option>
						<?php } ?>
					</select>
				</div>
				<?php
				
		}
		
		function addFromShortcode($atts, $content = null) {
			extract(shortcode_atts(array(
					'char' => '', 
					'realm' => '',
					'realmtype' => 'US',
					'gear' => 1,
					'profs' => 1,
					'achievs' => 1,
					'lang' => 'en',
					'linkback' => 0,
					'talents' => 1,
					'model' => 0,
					'hair' => 0,
					'hairColor' => 0,
					'face' => 0,
					'skinColor' => 0,
					'facialHair' => 0,
					'facialHairC' => 0,
					'top' => 1,
				), $atts));
				
			$randNo = rand(0, pow(10, 5));
			$results = '<div id="armory-'.$randNo.'" class="armory_display">';
			$armory = $this->getArmory(array(
				'cname' => $char,
				'realm' => $realm,
				'realmType' => $realmtype,
				'show_g' => $gear,
				'show_p' => $profs,
				'show_a' => $achievs,
				'lang' => $lang,
				'linkback' => $linkback,
				'talents' => $talents,
				'show3D' => $model,
				'hair' => $hair,
				'hairColor' => $hairColor,
				'face' => $face,
				'skinColor' => $skinColor,
				'facialHair' => $facialHair,
				'facialHairColor' => $facialHairC,
				'show_top' => $top,
				)
			);
			$results .= $armory['content'];
			$results .= '</div>';
			return "$results";
		}
		
		
		
		
		function getArmory($options) {
			/*
			// For Debug...
			echo "<pre>";
			print_r($options);
			echo "</pre>";
			*/
			$failed = false;
			
			$options['realmType'] = isset($options['realmType']) ? $options['realmType'] : "US";
			$rt = ($options['realmType'] == "EU" ? 'eu' : 'www');
			$options['realm'] = str_replace(" ","+",$options['realm']);
			$wl = isset($options['lang']) ? ($options['lang'] == 'en' ? 'www' : $options['lang']) : 'www';
			$baseURL = get_bloginfo('wpurl') . '/wp-content/plugins/wow-armory/';
			$url = "http://$rt.wowarmory.com/character-sheet.xml?r=".stripslashes($options['realm']).'&n='.stripslashes($options['cname']);
			
			if (get_option("lastarmory-".md5($options['cname'].'-'.$options['realm'].'-'.$options['realmType']))) {
				// If there is cached data for this character, grab it
				$armory_check = get_option("lastarmory-".md5($options['cname'].'-'.$options['realm'].'-'.$options['realmType']));
			} else {
				// else, leave it blank
				$armory_check = Array(
					'lastarmorycheck' => mktime() - 55000,
					'data' => false,
					'achiev' => false
				);
			}
			if ($armory_check['lastarmorycheck'] < ( mktime() - 54000 )	|| !$armory_check['data'] ) {
				$snoopy = new Snoopy();
				$snoopy->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
				$snoopy->fetch($url);
				$output = $snoopy->results;
				$armory_check['lastarmorycheck'] = mktime();
			} else {
				$output = $armory_check['data'];
			}
			
			if (!$output || $output == '') {
				$failed = true;
			} else {
				
				$parser = xml_parser_create();
				xml_parse_into_struct($parser, $output,$vals,$index);
				xml_parser_free($parser);
				if(!$vals) {
					$failed = true;
				} else {
					/* ------- Top -------- */
					$char_info = $vals[$index["CHARACTERINFO"][0]]["attributes"];
					if ($char_info['ERRCODE'] == "noCharacter") {
						$failed = true;
					} else {
						$char_attr = $vals[$index["CHARACTER"][0]]["attributes"];
						$results = array(
							'cname' => $char_attr["NAME"],
							'raceid' => $char_attr["RACEID"],
							'genderid' =>$char_attr["GENDERID"],
							'content' => '',
						);
							
						if ($options['show_top']) 
							$top_block .= "<img src=\"http://$rt.wowarmory.com/images/portraits/wow".($char_attr["LEVEL"] < 70 ? '' : ($char_attr["LEVEL"] < 80 ? '-70' : '-80'))."/".$char_attr["GENDERID"]."-".$char_attr["RACEID"]."-".$char_attr["CLASSID"].'.gif" width="48" class="armory_char_prof" /><span class="armory_char_name"><a href="'."http://$rt.wowarmory.com/character-sheet.xml?r=".stripslashes($options['realm'])."&n=".stripslashes($options['cname']).'">'.($char_attr["PREFIX"] ? $char_attr["PREFIX"].' ' : '').$char_attr["NAME"].($char_attr["SUFFIX"] ? $char_attr["SUFFIX"].' ' : '').'</a></span><br/><span class="armory_char_info" > of '.$char_attr["REALM"]."-".$options['realmType'].'<br/>Level '.$char_attr["LEVEL"].' '.$char_attr["RACE"].' '.$char_attr["CLASS"].'<br/>';
						
						/* === TALENTS === */
						if($options['talents']) {
							// if they want to show the Talents section
							$talents = $vals[$index["TALENTSPEC"][0]]["attributes"];
							if($talents['TREEONE'] >= $talents['TREETWO']) {
								if($talents['TREEONE'] >= $talents['TREETHREE']) {
									$spec = 1;
								} else {
									$spec = 3;
								}
							} else if($talents['TREETWO'] >= $talents['TREETHREE']) {
								$spec = 2;
							} else {
								$spec = 3;
							}
							$talent_block ='<img src="http://'.$rt.'.wowarmory.com/images/icons/class/'.$char_attr["CLASSID"].'/talents/'.$spec.'.gif" style="border:0;vertical-align:middle;margin-right:5px;" /><a href="http://'.$rt.'.wowarmory.com/character-talents.xml?r='.stripslashes($options['realm']).'&n='.stripslashes($options['cname']).'">'.$talents['TREEONE'].' / '.$talents['TREETWO'].' / '.$talents['TREETHREE'].'</a>';
						}
						if ($options['show_top'] || $options['talents'] ) {
							$top_block = '<div>'.$top_block;
							$talent_block .= '</div>';
						}
						/* =============== */
						
						/* ==== GEAR ===== */
						// if they don't want to show gear or the 3d model, we can skip this.
						if ($options['show_g'] || $options['show3D']) {
							
							$equipList = '';
							foreach($index["ITEM"] as $items) {
								$item = $vals[$items]["attributes"];
								if ($options['show3D']) {
									$itemDID = $this->getDID($item["ID"]);
										if ($itemDID['slot'] != 2 && $itemDID['slot'] != 11 && $itemDID['slot'] != 12 && $itemDID['slot'] != 14 && $itemDID['slot'] != 15) {
										$equipList.=(($equipList != '') ? ',' : '').($itemDID['slot']).','.$itemDID['did'];
									}
								}
								if ($options['show_g']) {
									if ($item["SLOT"] >= 0) {
										$enchants="lvl=".$char_attr["LEVEL"];								
										if ($item["PERMANENTENCHANT"] != "0")
											$enchants.=";ench=".$item["PERMANENTENCHANT"];
											
										if ($item["RANDOMPROPERTIESID"] != "0")
											$enchants.=";rand=".$item["RANDOMPROPERTIESID"];
										 
											if ($item["GEM0ID"] != "0" || $item["GEM1ID"] != "0" || $item["GEM1ID"] != "0") {
												$enchants.=";gems=";
												if ($item["GEM0ID"] != "0") 
													$enchants.=$item["GEM0ID"];
												if ($item["GEM1ID"] != "0") 
													$enchants.=":".$item["GEM1ID"];
												if ($item["GEM2ID"] != "0") 
													$enchants.=":".$item["GEM2ID"];
											}
											
										$equipDisplay .= '<li><a href="http://'.$wl.'.wowhead.com/?item='.$item["ID"].'"'.(($enchants) ? ' rel="'.$enchants.'"' : '').'>';
										$equipDisplay .= '<img src="http://'.$rt.'.wowarmory.com/wow-icons/_images/51x51/'.$item["ICON"].'.jpg" width="26" border="0" class="armory_item_icon"/>';
										$equipDisplay .= '</a></li>';
									}
								}
							}
							if ($options['show_g'])
								$equipDisplay = '<h4>Equipment</h4><ul class="armory_equip_list">'.$equipDisplay.'</ul>';
						}
						/* =============== */
						
						/* === 3D model == */
						if ($options['show3D']) {
							$model3D = $this->modelNames[$char_attr["RACEID"]][$char_attr["GENDERID"]];
							$model_block = $this->get3DModel($model3D, $options, $equipList);
						}
						/* =============== */
						
						
						/* == Profession = */
						if ($options['show_p']){
							$prof_1 = $vals[$index["SKILL"][0]]["attributes"];
							$prof_2 = $vals[$index["SKILL"][1]]["attributes"];
							if ($prof_1 != NULL && $prof_2 != NULL) {
								$prof_block = '<h4>Professions</h4><ul class="armory_prof_list">';
								if ($prof_1 != NULL) {
									$prof_block .= '<li><img src="http://static.wowhead.com/images/icons/small/'.$prof_img[$prof_1["NAME"]].'.jpg" width="16" />&nbsp;&nbsp;<span class="armory_prof_name">'.$prof_1["NAME"].':</span> '.$prof_1["VALUE"].'/'.$prof_1["MAX"].'</li>';
								}
								if ($prof_2 != NULL) {
									$prof_block .= '<li><img src="http://static.wowhead.com/images/icons/small/'.$prof_img[$prof_2["NAME"]].'.jpg" width="16" />&nbsp;&nbsp;<span class="armory_prof_name">'.$prof_2["NAME"].':</span> '.$prof_2["VALUE"].'/'.$prof_2["MAX"].'</li>';
									
								}
								$prof_block .= '</ul>';
							}
						}
						/* =============== */
						
						/* = Achievements = */
						if ($options['show_a']) {
							$urla = "http://$rt.wowarmory.com/character-achievements.xml?r=".stripslashes($options['realm']).'&n='.stripslashes($options['cname']);
							
							if ($armory_check['achiev'] && $armory_check['achiev'] != '' ) {
								$output_achiev = $armory_check['achiev'];
							} else {
								$snoopya = new Snoopy();
								$snoopya->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
								$snoopya->fetch($urla);
								$output_achiev = $snoopya->results;
							}
							$parser_achiev = xml_parser_create();
							xml_parse_into_struct($parser_achiev,$output_achiev,$vals_a,$index_a);
							xml_parser_free($parser_achiev);
							if ($vals_a) {
								$achiev_block = '<h4>Recent Achievements</h4><ul class="armory_achiev_list">';
								foreach($index_a["ACHIEVEMENT"] as $achs) {
									$ach = $vals_a[$achs]["attributes"];
									$achiev_block .= '<li><a href="http://'.$wl.'.wowhead.com/?achievement='.$ach["ID"].'" ><img src="http://'.$rt.'.wowarmory.com/wow-icons/_images/51x51/'.$ach["ICON"].'.jpg" width="20" border="0" class="armory_achiev_icon"/>'.$ach["TITLE"].'</a></li>';
								}
								$achiev_block .= '</ul>';
							}
						}
						/* =============== */
						
						if ($options['linkback']) 
							$linkback = '<br/><p style="text-align:right;"><a href="http://timsworld.nfshost.com"><img src="'.$baseURL.'powered_by.png" style="border:0;"/></a></p>';
					}
				}
			}
			if(!$failed) {
				$armory_check['data'] = $output;
				$armory_check['achiev'] = $output_achiev;
				
				$armory_check['crealm'] = $char_attr["REALM"];
				$armory_check['raceid'] = $char_attr["RACEID"];
				$armory_check['realmType'] = $options['realmType'];
				$armory_check['lang'] = $options['lang'];
				
				$results['content'] = $top_block.$talent_block.$model_block.$equipDisplay.$prof_block.$achiev_block.$linkback;
				if (get_option("lastarmory-".md5($options['cname'].'-'.$options['realm'].'-'.$options['realmType']))) {
					update_option("lastarmory-".md5($options['cname'].'-'.$options['realm'].'-'.$options['realmType']),$armory_check);
				} else {
					add_option("lastarmory-".md5($options['cname'].'-'.$options['realm'].'-'.$options['realmType']),$armory_check);
				}
			} else {
				$results['content'] = '<p>Armory is currently unavailable...</p>';
			}
			return $results;

		}
		
		
		
		function get3DModel($model,$modeldata,$equipList) {
			$results = '<object id="wowhead" width="250" height="400" type="application/x-shockwave-flash" data="http://static.wowhead.com/modelviewer/ModelView.swf"><param name="quality" value="high"/><param name="allowscriptaccess" value="always"/><param name="menu" value="false"/><param value="transparent" name="wmode"><param name="flashvars" value="contentPath=http://static.wowhead.com/modelviewer/&blur=1';
			$results .= '&model='.$model;
			$results .= '&modelType=16';
			$results .= '&ha='.$modeldata['hairStyle'];
			$results .= '&hc='.$modeldata['hairColor'];
			$results .= '&fa='.$modeldata['face'];
			$results .= '&sk='.$modeldata['skinColor'];
			$results .= '&fh='.$modeldata['facialHair'];
			$results .= '&fc='.$modeldata['facialHairColor'];
			$results .= '&equipList='.$equipList.'"/>';
			$results .= '</object>';
			return $results;
		}
		
		function getDID($itemID) {
			$url = 'http://www.wowhead.com/?item='.$itemID.'&xml';
			$snoopy = new Snoopy();
			$snoopy->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
			$snoopy->fetch($url);
			$output = $snoopy->results;
			$parser = xml_parser_create();
			xml_parse_into_struct($parser,$output,$vals,$index);
			xml_parser_free($parser);
			$icon = $vals[$index["ICON"][0]]["attributes"];
			$slot = $vals[$index["INVENTORYSLOT"][0]]["attributes"];
			return Array('did' => $icon["DISPLAYID"], 'slot' => $slot["ID"]);
		}
		
	}
function wowarmory_options_page() {
$wrmAdmin = new WoWArmory();
	?>
	<div class="wrap">
		<h2>wow-armory Cache Administration</h2>
		<form id="cache-list" action="" method="get">
			<input type="hidden" value="wowarmorycache" name="page" />
			
			<div class="tablenav">
				<input type="submit" value="Refresh" name="refresh" class="button-secondary" />
				<input type="submit" value="Clear Cache" name="deleteit" class="button-secondary delete" />
				<br class="clear" />
			</div>

			<br class="clear" />
			
			<table class="widefat">
				<thead>
					<tr>
						<th scope="col" class="check-column"><input type="checkbox" onclick="checkAll(document.getElementById('cache-list'));" /></th>
						<th scope="col">Character Name</th>
						<th scope="col">Realm</th>
						<th scope="col">Realm Type</th>
						<th scope="col">Last Cache</th>
						<th scope="col"></th>
					</tr>
				</thead>
				
				<tbody>
					<?php 
						global $wpdb;
						$caches = $wpdb->get_results("SELECT * FROM wp_options WHERE `option_name` LIKE '%lastarmory%' ");
						if (count($caches)==0) {
						?>
							<tr>
								<td scope="row" colspan="4" style="text-align: center;"><strong>No Caches Found</strong></td>
							</tr>
						<?php
						} else {
							foreach ($caches as $cache) {
								$currentCache = get_option($cache->option_name);
								$parser = xml_parser_create();
								xml_parse_into_struct($parser,$currentCache['data'],$vals,$index);
								xml_parser_free($parser);
								$char_info = $vals[$index["CHARACTERINFO"][0]]["attributes"];
								$char_attr = $vals[$index["CHARACTER"][0]]["attributes"];
								$armory = $wrmAdmin->getArmory(array(
										'cname' => $char_attr["NAME"] ,
										'realm' => $char_attr["REALM"],
										'realmType' => $currentCache['realmType'],
										'show_g' => 1,
										'show_p' => 1,
										'show_a' => 1,
										'lang' => $currentCache['lang'],
										'linkback' => 1,
										'talents' => 1,
										'show3D' => 1,
										'hair' => 0,
										'hairColor' => 0,
										'face' => 0,
										'skinColor' => 0,
										'facialHair' => 0,
										'facialHairColor' => 0,
										'show_top' => 1,
									)
								);
								?>
								<tr>
									<th scope="row" class="check-column"><input type="checkbox" name="delete[]" value="<?php echo $cache->option_name; ?>" /></th>
									<td scope="row" style="text-align: left"><img src="http://www.wowarmory.com/images/icons/race/<?php echo $char_attr['RACEID'].'-'.$char_attr['GENDERID']; ?>.gif"/> <img src="http://www.wowarmory.com/images/icons/class/<?php echo $char_attr['CLASSID']; ?>.gif" /> <?php echo $char_attr["NAME"]; ?></td>
									<td scope="row" style="text-align: left"><?php echo $char_attr["REALM"]; ?></td>
									<td scope="row" style="width:60px;text-align: left"><?php echo $currentCache['realmType']; ?></td>
									<td scope="row" style="text-align: left"><?php echo date("F j, Y, g:i a", $currentCache['lastarmorycheck']); ?></td>
									<td scope="row" style="width:140px;text-align:center;"><input alt="#TB_inline?height=500&width=400&inlineId=cache-<?php echo $cache->option_name; ?>" title="Armory for <?php echo $char_attr["NAME"]; ?>" class="thickbox button-secondary" type="button" value="View &raquo;" />
									<div id="cache-<?php echo $cache->option_name; ?>" style="display:none;"><?php 
									
									
									echo $armory['content'];
									
									 ?></div></td>
								
								</tr>
								<?php
							}
						}
					?>
				</tbody>
			</table>
			<div class="tablenav">
				<br class="clear" />
			</div>
		</form>	
	</div>
	<?php
}

function wowarmory_add_pages() {
			$page_name = add_options_page('wow-armory Cache Administration', 'wow-armory Cache', 8, 'wowarmorycache', 'wowarmory_options_page');
			add_action('admin_head-'.$page_name,'thickbox_css');
		}

function thickbox_css() {
	echo '<link rel="stylesheet" href="'.get_bloginfo('wpurl').'/wp-content/plugins/wow-armory/includes/thickbox/thickbox.css" type="text/css" />';

}



$wrm = new WoWArmory();
add_action('widgets_init', array($wrm, 'init'));
add_shortcode("wowarmory", array($wrm, 'addFromShortcode'));
add_action('admin_menu', 'wowarmory_add_pages');
wp_enqueue_script('thickbox',get_bloginfo('wpurl') . '/wp-content/plugins/wow-armory/includes/thickbox/thickbox-compressed.js', array('jquery'));

?>